/**
 * 200. 岛屿数量
 */
public class Solution_200 {
    /**
     * 深度优先搜索
     * <p>
     * 时间复杂度：O(MN)
     * <p>
     * 空间复杂度：O(MN)
     */
    public int numIslands(char[][] grid) {
        if (grid == null | grid.length == 0) {
            return 0;
        }
        int row = grid.length, col = grid[0].length;
        int ans = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == '1') {
                    ans++;
                    dfs(grid, i, j);
                }
            }
        }
        return ans;
    }

    public void dfs(char[][] grid, int i, int j) {
        int row = grid.length, col = grid[0].length;
        if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == '0') {
            return;
        }

        // 标记已访问
        grid[i][j] = '0';

        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }

    public static void main(String[] args) {
        Solution_200 solution = new Solution_200();
        char[][] grid = { 
            { '1', '1', '0', '0', '0' }, 
            { '1', '1', '0', '0', '0' }, 
            { '0', '0', '1', '0', '0' },
            { '0', '0', '0', '1', '1' } 
        };
        int ans = solution.numIslands(grid);
        System.out.println(ans);
    }
}
